<template>
  <div class="product-management">
    <div class="page-header">
      <h2>商品管理</h2>
      <el-button type="primary" @click="handleAdd">添加商品</el-button>
    </div>

    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="query" class="search-form">
        <el-form-item label="商品名称">
          <el-input v-model="query.name" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品分类">
          <el-select v-model="query.category" placeholder="请选择分类">
            <el-option label="全部" value=""></el-option>
            <el-option
              v-for="category in categories"
              :key="category.value"
              :label="category.label"
              :value="category.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 商品列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="products"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          width="80">
        </el-table-column>
        <el-table-column
          prop="name"
          label="商品名称"
          min-width="200">
        </el-table-column>
        <el-table-column
          prop="category"
          label="分类"
          width="120">
          <template slot-scope="scope">
            {{ getCategoryLabel(scope.row.category) }}
          </template>
        </el-table-column>
        <el-table-column
          label="图片"
          width="120"
          align="center">
          <template slot-scope="scope">
            <el-image
              v-if="scope.row.imageUrl"
              :src="getImageUrl(scope.row.imageUrl)"
              :preview-src-list="[getImageUrl(scope.row.imageUrl)]"
              style="width: 80px; height: 80px;"
              fit="cover">
            </el-image>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="价格"
          width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.price }}
          </template>
        </el-table-column>
        <el-table-column
          prop="stock"
          label="库存"
          width="100">
        </el-table-column>
        <el-table-column
          prop="sales"
          label="销量"
          width="100">
        </el-table-column>
        <el-table-column
          label="状态"
          width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '在售' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="200"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              size="mini"
              @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query.pageNum"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="query.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 添加/编辑商品对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px">
      <el-form
        :model="productForm"
        :rules="rules"
        ref="productForm"
        label-width="100px">
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="productForm.name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="category">
          <el-select v-model="productForm.category" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input-number
            v-model="productForm.price"
            :precision="2"
            :step="0.1"
            :min="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品库存" prop="stock">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            :precision="0">
          </el-input-number>
        </el-form-item>
        <el-form-item label="商品图片" prop="imageUrl">
          <el-upload
            class="product-image-uploader"
            :action="uploadUrl"
            :http-request="handleFileUpload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <img v-if="productForm.imageUrl" :src="getImageUrl(productForm.imageUrl)" class="product-image">
            <i v-else class="el-icon-plus product-image-uploader-icon"></i>
          </el-upload>
          <div v-if="productForm.imageUrl" class="image-actions">
            <el-button type="text" size="small" @click="previewImage">预览图片</el-button>
            <el-button type="text" size="small" @click="removeImage">删除图片</el-button>
          </div>
        </el-form-item>
        <el-form-item label="商品描述" prop="description">
          <el-input
            type="textarea"
            v-model="productForm.description"
            :rows="4">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getProductList, createProduct, updateProduct, deleteProduct, uploadFile } from '@/api/admin'
import { getProductCategories } from '@/api/product'
import { getToken } from '@/utils/auth'

export default {
  name: 'ProductManagement',
  
  data() {
    return {
      loading: false,
      products: [],
      total: 0,
      query: {
        pageNum: 1,
        pageSize: 10,
        name: '',
        category: '',
        status: ''
      },
      productForm: {
        id: null,
        name: '',
        category: '',
        price: '',
        description: '',
        imageUrl: '',
        stock: '',
        status: 1
      },
      rules: {
        name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        category: [{ required: true, message: '请选择商品类别', trigger: 'change' }],
        price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        stock: [{ required: true, message: '请输入商品库存', trigger: 'blur' }]
      },
      dialogVisible: false,
      dialogTitle: '添加商品',
      categories: [],
      statusOptions: [
        { label: '上架', value: 1 },
        { label: '下架', value: 0 }
      ],
      uploadUrl: '/api/files/upload?directory=products',
      uploadHeaders: {
        Authorization: 'Bearer ' + getToken()
      }
    }
  },
  
  created() {
    this.fetchProducts()
    this.fetchCategories()
  },
  
  methods: {
    async fetchCategories() {
      try {
        const response = await getProductCategories()
        if (response.code === 200 && response.data) {
          this.categories = response.data
        } else {
          // 如果API获取失败，使用默认分类
          this.categories = [
            { value: 'food', label: '宠物食品' },
            { value: 'toys', label: '玩具用品' },
            { value: 'health', label: '保健品' },
            { value: 'daily', label: '日用品' },
            { value: 'cleaning', label: '清洁用品' },
            { value: 'other', label: '其他' }
          ]
        }
      } catch (error) {
        console.error('获取商品分类失败:', error)
        // 使用默认分类
        this.categories = [
          { value: 'food', label: '宠物食品' },
          { value: 'toys', label: '玩具用品' },
          { value: 'health', label: '保健品' },
          { value: 'daily', label: '日用品' },
          { value: 'cleaning', label: '清洁用品' },
          { value: 'other', label: '其他' }
        ]
      }
    },
    
    async fetchProducts() {
      try {
        this.loading = true
        const params = {
          pageNum: this.query.pageNum,
          pageSize: this.query.pageSize,
          name: this.query.name,
          category: this.query.category,
          status: this.query.status
        }
        const response = await getProductList(params)
        if (response.code === 200 && response.data) {
          this.products = response.data.list
          this.total = response.data.total
        }
      } catch (error) {
        this.$message.error('获取商品列表失败')
      } finally {
        this.loading = false
      }
    },
    
    // 获取图片URL的方法
    getImageUrl(path) {
      // 如果路径为空，返回空字符串
      if (!path) return '';
      
      // 获取当前窗口的主机名和端口
      const serverUrl = 'http://localhost:8080'; // 后端API服务器地址
      
      // 如果已经是完整URL，直接返回
      if (path.startsWith('http://') || path.startsWith('https://')) {
        return path;
      }
      
      // 确保路径以/开头
      const normalizedPath = path.startsWith('/') ? path : '/' + path;
      
      // 返回完整URL
      return serverUrl + normalizedPath;
    },
    
    getCategoryLabel(value) {
      const category = this.categories.find(c => c.value === value);
      return category ? category.label : '未分类';
    },
    
    handleSearch() {
      this.query.pageNum = 1
      this.fetchProducts()
    },
    
    resetSearch() {
      this.query.name = ''
      this.query.category = ''
      this.query.status = ''
      this.handleSearch()
    },
    
    handleSizeChange(val) {
      this.query.pageSize = val
      this.fetchProducts()
    },
    
    handleCurrentChange(val) {
      this.query.pageNum = val
      this.fetchProducts()
    },
    
    handleAdd() {
      this.dialogTitle = '添加商品'
      this.productForm = {
        id: null,
        name: '',
        category: '',
        price: '',
        description: '',
        imageUrl: '',
        stock: '',
        status: 1
      }
      this.dialogVisible = true
    },
    
    handleEdit(row) {
      this.dialogTitle = '编辑商品'
      this.productForm = { ...row }
      this.dialogVisible = true
    },
    
    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该商品吗？', '提示', {
          type: 'warning'
        })
        const response = await deleteProduct(row.id)
        if (response.code === 200) {
          this.$message.success('删除成功')
          this.fetchProducts()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    
    async submitForm() {
      try {
        await this.$refs.productForm.validate()
        let response
        if (!this.productForm.id) {
          response = await createProduct(this.productForm)
        } else {
          response = await updateProduct(this.productForm.id, this.productForm)
        }
        if (response.code === 200) {
          this.$message.success(!this.productForm.id ? '添加成功' : '更新成功')
          this.dialogVisible = false
          this.fetchProducts()
        }
      } catch (error) {
        this.$message.error(!this.productForm.id ? '添加失败' : '更新失败')
      }
    },
    
    handleUploadSuccess(response) {
      if (response && response.code === 200) {
        this.productForm.imageUrl = response.data
        this.$message.success('上传成功')
      } else {
        this.$message.error(response.message || '上传失败')
      }
    },
    
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!')
        return false
      }
      return true
    },
    
    handleFileUpload(event) {
      const file = event.file;
      console.log('上传文件:', file.name, file.size);
      
      const formData = new FormData();
      formData.append('file', file);
      formData.append('directory', 'products');

      console.log('开始上传到服务器');
      uploadFile(formData, {
        headers: {
          Authorization: 'Bearer ' + getToken(),
          'Content-Type': 'multipart/form-data'
        }
      }).then(response => {
        console.log('上传响应:', response);
        if (response.code === 200) {
          this.productForm.imageUrl = response.data;
          this.$message.success('上传成功');
        } else {
          console.error('上传失败:', response.message);
          this.$message.error(response.message || '上传失败');
        }
      }).catch(error => {
        console.error('上传请求错误:', error);
        this.$message.error('上传失败: ' + (error.message || '未知错误'));
      });
    },
    
    previewImage() {
      if (!this.productForm.imageUrl) return;
      
      // 创建一个临时的大图预览
      const url = this.getImageUrl(this.productForm.imageUrl);
      const previewList = [url];
      
      // 使用Element UI的图片预览功能
      this.$image({
        urls: previewList,
        closeOnClickModal: true
      });
    },
    
    removeImage(event) {
      // 阻止事件冒泡，防止触发上传
      if (event) {
        event.stopPropagation();
      }
      
      // 清除图片相关数据
      this.productForm.imageUrl = '';
      
      this.$message.success('图片已删除');
      
      // 强制刷新视图
      this.$forceUpdate();
    }
  }
}
</script>

<style lang="scss" scoped>
.product-management {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
    }
  }
  
  .search-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .pagination-container {
      margin-top: 20px;
      text-align: right;
    }
  }
  
  .product-image-uploader {
    .product-image {
      width: 148px;
      height: 148px;
      display: block;
      object-fit: cover;
      border-radius: 4px;
      border: 1px solid #eee;
    }
    
    .product-image-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      line-height: 148px;
      text-align: center;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      
      &:hover {
        border-color: #409EFF;
      }
    }
  }
  
  .image-actions {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    gap: 10px;
  }
}
</style> 